﻿/////////////////////////////////////////////////
//文件名:File
//描  述:
//创建者:刘凡平(Iveely Liu)
//邮  箱:945222889@qq.com
//组  织:Iveely
//年  份:2012/5/11 14:59:26
///////////////////////////////////////////////


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using IveelySE.BigData.Common;
using System.Threading;

namespace IveelySE.BigData.FileSystem
{
    /// <summary>
    /// 文件操作
    /// </summary>
    public class File
    {
        /// <summary>
        /// 配置信息
        /// </summary>
        private static Config Config = new Config();

        /// <summary>
        /// 向文件追写数据，如果文件不存在则创建
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="data">需要写入的数据</param>
        public static void AppendText(string fileName, Object obj)
        {
            //建立数据对象
            PObject pobj = new PObject(fileName, obj);
            //ParameterizedThreadStart myParameterizedThreadDelegate = new ParameterizedThreadStart(appendText);
            ////启用线程去操作
            //Thread thread = new Thread(myParameterizedThreadDelegate);
            ////启动
            //thread.Start(pobj);
            //新建客户端
            BigData.Common.Communication.Transfer.Client client = new Common.Communication.Transfer.Client(Config.MasterIP, Config.WritePort);
            //向服务端发送
            client.ConnectToServer(pobj);
            Thread.Sleep(1);
           
        }
        /// <summary>
        /// 写线程函数
        /// </summary>
        /// <param name="pobj"></param>
        private static void appendText(Object pobj)
        {
            pobj = (PObject)pobj;
            //新建客户端
            BigData.Common.Communication.Transfer.Client client = new Common.Communication.Transfer.Client(Config.MasterIP, Config.WritePort);
            //向服务端发送
            client.ConnectToServer(pobj);
        }

        /// <summary>
        /// 读某文件的一行数据
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="lineNum">文件行号</param>
        public static object ReadLine(string fileName, int lineNum)
        {
            //如果行号小于0
            if (lineNum < 0)
            {
                //则返回空
                return null;
            }
            //新建传输对象
            PObject pobj = new PObject(fileName, lineNum);
            //新建客户端
            Common.Communication.Transfer.Client client = new Common.Communication.Transfer.Client(Config.MasterIP, Config.ReadPort);
            //向服务端发送请求
            object obj = client.ConnectToServer(pobj);
            //返回读取的对象
            return obj!=null?((PObject)obj).value:-1;

        }
    }
}
